package view;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class QuestionBankSystem extends JInternalFrame {
    private JTextField numberField;
    private JButton generateButton;
    private JButton refreshButton;
    private JTable questionTable;
    private DefaultTableModel tableModel;
    private JTable selectedQuestionTable;
    private DefaultTableModel selectedTableModel;

    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/exam";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    // 存储所有题目
    private List<Question> allQuestions = new ArrayList<>();

    public QuestionBankSystem() {
        super("题库抽题系统", true, true, true, true);
        initializeUI();
        loadQuestionsFromDatabase();
    }

    private void initializeUI() {
        setSize(1000, 700);
        setLayout(new BorderLayout(5, 5));

        // 顶部面板 - 控制区域
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        controlPanel.add(new JLabel("抽取题目数量:"));
        numberField = new JTextField(5);
        controlPanel.add(numberField);

        generateButton = new JButton("随机抽题");
        generateButton.addActionListener(e -> generatePaper());
        controlPanel.add(generateButton);

        refreshButton = new JButton("刷新题库");
        refreshButton.addActionListener(e -> loadQuestionsFromDatabase());
        controlPanel.add(refreshButton);

        add(controlPanel, BorderLayout.NORTH);

        // 中间面板 - 分割面板显示题库和已选题目
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setDividerLocation(350);
        splitPane.setResizeWeight(0.5);

        // 题库表格
        tableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }
        };
        tableModel.addColumn("ID");
        tableModel.addColumn("题目内容");
        tableModel.addColumn("选项A");
        tableModel.addColumn("选项B");
        tableModel.addColumn("选项C");
        tableModel.addColumn("选项D");
        tableModel.addColumn("正确答案");

        questionTable = new JTable(tableModel);
        questionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane questionScrollPane = new JScrollPane(questionTable);
        questionScrollPane.setBorder(BorderFactory.createTitledBorder("题库内容"));

        // 已选题目表格
        selectedTableModel = new DefaultTableModel();
        selectedTableModel.addColumn("ID");
        selectedTableModel.addColumn("题目内容");
        selectedTableModel.addColumn("选项A");
        selectedTableModel.addColumn("选项B");
        selectedTableModel.addColumn("选项C");
        selectedTableModel.addColumn("选项D");
        selectedTableModel.addColumn("正确答案");

        selectedQuestionTable = new JTable(selectedTableModel);
        JScrollPane selectedScrollPane = new JScrollPane(selectedQuestionTable);
        selectedScrollPane.setBorder(BorderFactory.createTitledBorder("已选题目"));

        splitPane.setTopComponent(questionScrollPane);
        splitPane.setBottomComponent(selectedScrollPane);

        add(splitPane, BorderLayout.CENTER);

        // 底部面板 - 状态信息
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statusPanel.add(new JLabel("题库中共有题目: 0 道"));
        add(statusPanel, BorderLayout.SOUTH);
    }

    private void loadQuestionsFromDatabase() {
        allQuestions.clear();
        tableModel.setRowCount(0);

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM questions")) {

            while (rs.next()) {
                Question question = new Question(
                        rs.getInt("id"),
                        rs.getString("question_text"),
                        rs.getString("option_a"),
                        rs.getString("option_b"),
                        rs.getString("option_c"),
                        rs.getString("option_d"),
                        rs.getString("correct_answer")
                );
                allQuestions.add(question);

                tableModel.addRow(new Object[]{
                        question.getId(),
                        question.getQuestionText(),
                        question.getOptionA(),
                        question.getOptionB(),
                        question.getOptionC(),
                        question.getOptionD(),
                        question.getCorrectAnswer()
                });
            }

            // 更新状态栏
            ((JLabel)((JPanel)getContentPane().getComponent(2)).getComponent(0)).setText(
                    "题库中共有题目: " + allQuestions.size() + " 道");

        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "加载题库失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void generatePaper() {
        try {
            int n = Integer.parseInt(numberField.getText());
            int totalQuestions = allQuestions.size();

            if (n <= 0) {
                JOptionPane.showMessageDialog(this, "请输入大于0的数字", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (n > totalQuestions) {
                JOptionPane.showMessageDialog(this,
                        "题库中只有 " + totalQuestions + " 道题目，无法抽取 " + n + " 道",
                        "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 随机抽题
            selectedTableModel.setRowCount(0); // 清空已选题目

            List<Question> shuffled = new ArrayList<>(allQuestions);
            Collections.shuffle(shuffled, new Random());

            for (int i = 0; i < n; i++) {
                Question q = shuffled.get(i);
                selectedTableModel.addRow(new Object[]{
                        q.getId(),
                        q.getQuestionText(),
                        q.getOptionA(),
                        q.getOptionB(),
                        q.getOptionC(),
                        q.getOptionD(),
                        q.getCorrectAnswer()
                });
            }

            JOptionPane.showMessageDialog(this,
                    "成功随机抽取 " + n + " 道题目", "成功", JOptionPane.INFORMATION_MESSAGE);

        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 题目实体类
    private static class Question {
        private int id;
        private String questionText;
        private String optionA;
        private String optionB;
        private String optionC;
        private String optionD;
        private String correctAnswer;

        public Question(int id, String questionText, String optionA, String optionB,
                        String optionC, String optionD, String correctAnswer) {
            this.id = id;
            this.questionText = questionText;
            this.optionA = optionA;
            this.optionB = optionB;
            this.optionC = optionC;
            this.optionD = optionD;
            this.correctAnswer = correctAnswer;
        }

        // Getter方法
        public int getId() { return id; }
        public String getQuestionText() { return questionText; }
        public String getOptionA() { return optionA; }
        public String getOptionB() { return optionB; }
        public String getOptionC() { return optionC; }
        public String getOptionD() { return optionD; }
        public String getCorrectAnswer() { return correctAnswer; }
    }

    public static void main(String[] args) {
        // 测试代码
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("题库抽题系统测试");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(1020, 720);

            JDesktopPane desktopPane = new JDesktopPane();
            frame.setContentPane(desktopPane);

            QuestionBankSystem system = new QuestionBankSystem();
            desktopPane.add(system);
            system.setVisible(true);

            frame.setVisible(true);
        });
    }
}